// Copyright 2008 and onwards Matt Burkhart, Mike Chan.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.

#include <assert.h>
#include <stdarg.h>
#include <string.h>

#include "logger.h"

using namespace std;

DiskLogger::DiskLogger(const char log_file_path[]) {
  assert((disk_log_ = fopen(log_file_path, "a")) != NULL);
  pthread_mutex_init(&disk_log_lock_, NULL);
}

DiskLogger::~DiskLogger() {
  fclose(disk_log_);
  pthread_mutex_destroy(&disk_log_lock_);
}

void DiskLogger::Log(const char message[], ...) {
  // The lock is required to include the calls to time and ctime since they are
  // not necessarily thread-safe.
  pthread_mutex_lock(&disk_log_lock_);

  time_t timestamp = time(NULL);
  char* timestamp_string = ctime(&timestamp);
  size_t timestamp_string_length = strlen(timestamp_string);
  assert(timestamp_string_length > 0);
  timestamp_string[timestamp_string_length - 1] = '\0';

  va_list argp;
  va_start(argp, message);
  fprintf(disk_log_, "[%s] ", timestamp_string);
  vfprintf(disk_log_, message, argp);
  fprintf(disk_log_, "\n");
  va_end(argp);
  fflush(disk_log_);

  pthread_mutex_unlock(&disk_log_lock_);
}
